import 'dart:convert';
import 'dart:io';
import 'package:flutter_learning/isolate/utils/ly_log.dart';

class LYServerSocketManager {
  Future<void> startSocketServer() async {
    try {
      // 创建ServerSocket并监听指定端口，这里以8888端口为例
      ServerSocket serverSocket = await ServerSocket.bind('127.0.0.1', 8888);
      // 开始处理客户端连接
      serverSocket.listen((socket) {
        handleClientData(socket);
      });
    } catch (e) {
      LYLog.d('启动Socket服务失败：$e');
    }
  }

  void handleClientData(Socket clientSocket) async {
    // 接收客户端发送的数据
    clientSocket.listen((List<int> data) {
      String receivedData = utf8.decode(data);
      LYLog.d('从客户端接收的数据：$receivedData');
      // 这里可以根据接收到的数据进行相应处理，比如回复客户端等
      String response = '已收到你的消息：$receivedData';
      clientSocket.write(utf8.encode(response));
    }, onError: (error) {
      LYLog.d('接收客户端数据出错：$error');
      clientSocket.close();
    }, onDone: () {
      LYLog.d('客户端连接已关闭');
      clientSocket.close();
    });
  }
}
